
#include <QDebug>
#include <QUuid>
#include <QThread>

#include "task.h"

class TaskPrivate
{
public:
    TaskPrivate(Task *parent = nullptr);
    ~TaskPrivate();

    TaskData data;

private:
    Task * const q_ptr;
    Q_DECLARE_PUBLIC(Task)
};

TaskPrivate::TaskPrivate(Task *parent) : q_ptr(parent)
{
    qRegisterMetaType<QProcess::ProcessState>("QProcess::ProcessState");
    qRegisterMetaType<QProcess::ExitStatus>("QProcess::ExitStatus");
}

TaskPrivate::~TaskPrivate()
{
    data.reset();
}

Task::Task(const TaskData &task, QObject *parent) : QProcess{parent}, d_ptr(new TaskPrivate(this))
{
    Q_D(Task);
    d->data = task;
    this->setProgram(d->data.exec);
    this->setArguments(d->data.args);
}

Task::~Task()
{}

const TaskData &Task::data()
{ Q_D(Task); return d->data; }

const QString &Task::name()
{ Q_D(Task); return d->data.name; }

const QString &Task::uuid()
{ Q_D(Task); return d->data.uuid; }

bool Task::is_running()
{ return (this->state() == QProcess::Running); }

void Task::Start()
{
    this->start(QIODevice::ReadOnly | QIODevice::Unbuffered);
}

void Task::Stop(bool force)
{
    if (force) {
        this->kill();
    } else {
        this->terminate();
        // TODO: 添加一个监视线程等待进程退出
    }
    this->waitForFinished();
}
